//
//  ZTTools.m
//  STIM
//
//  Created by 帅拓 on 2016/12/13.
//  Copyright © 2016年 赵甜. All rights reserved.
//

#import "ZTTools.h"

@implementation ZTTools


#pragma mark - check String is Empty
+ (BOOL)isEmpty:(NSString *)string
{
    if (![string isKindOfClass:[NSString class]])
        string = [string description];
    if (string == nil || string == NULL)
        return YES;
    if ([string isKindOfClass:[NSNull class]])
        return YES;
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0)
        return YES;
    if ([string isEqualToString:@"(null)"])
        return YES;
    if ([string isEqualToString:@"(null)(null)"])
        return YES;
    if ([string isEqualToString:@"<null>"])
        return YES;
    if ([string isEqualToString:@""])
        return YES;
    // return Default
    return NO;
}

#pragma mark showAlert
+(void)showAlert:(NSString *)message
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
    
}


#pragma mark //通过文字长度计算高度，
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    if (![ZTTools isEmpty:text]) {
        return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    }else{
        return CGSizeMake(0, 0);
    }
}

#pragma mark 等比缩放
+(UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}


+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
//    if (aImage.imageOrientation == UIImageOrientationUp)
//        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_4);
            break;
            
        case UIImageOrientationUp:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 50, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


//字符串去除特殊字符

+(NSString *)removeSpecialChar:(NSString *)tempstr{

    NSString *b = [tempstr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/n\" "]];//该方法是去掉指定符号
    NSString *c = [b stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];//该方法是去掉指定符号
    NSString *strUrl = [c stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return strUrl;
}

//字符串排序
+(NSString *)StringToSorting:(NSString *)strUrl{
    NSMutableArray *  strArray = [[NSMutableArray alloc]init];
    for (int i=0 ;i<strUrl.length;i++)
    {
        
        unichar theChar = [strUrl characterAtIndex:i];
        NSString * tempC = [NSString stringWithFormat:@"%C", theChar];
        [strArray addObject:tempC];
    }
    NSLog(@"%@",strArray);
    
    
    NSArray *myary = [strArray sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
        return (NSComparisonResult)[obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    NSString * ztStr =@"";
    for (int a = 0;a< myary.count ; a++) {
        NSString * str =myary[a];
        ztStr = [NSString stringWithFormat:@"%@%@",ztStr,str];
    }
    return ztStr;
}


//获取顶层控制器
+(UIViewController *)theTopviewControler{
    UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
    
    UIViewController *parent = rootVC;
    
    while ((parent = rootVC.presentedViewController) != nil ) {
        rootVC = parent;
    }
    
    while ([rootVC isKindOfClass:[UINavigationController class]]) {
        rootVC = (UINavigationController *)rootVC.navigationController.viewControllers[rootVC.navigationController.viewControllers.count]; //[(UINavigationController *)rootVC topViewController];
    }
    
    return rootVC;
}

+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}


//星期转化
+(NSString * )weekDay_Eng_TO_Ch:(NSString *)Str{
    NSArray* array = [Str componentsSeparatedByString:@","];
    
    NSString *  string;
    NSMutableArray * tempArray = [[NSMutableArray alloc]init];

    for (NSString * tempStr  in array) {
        if ([tempStr isEqualToString:@"Monday"]) {
            string = [NSString stringWithFormat:@"%@",@"星期一"];
        }else if([tempStr isEqualToString:@"Tuesday"]){
            string  = [NSString stringWithFormat:@"%@",@"星期二"];
        }else if([tempStr isEqualToString:@"Wednesday"]){
            string  = [NSString stringWithFormat:@"%@",@"星期三"];
        }else if([tempStr isEqualToString:@"Thursday"]){
            string  = [NSString stringWithFormat:@"%@",@"星期四"];
        }else if([tempStr isEqualToString:@"Friday"]){
            string  = [NSString stringWithFormat:@"%@",@"星期五"];
        }else if([tempStr isEqualToString:@"Saturday"]){
            string  = [NSString stringWithFormat:@"%@",@"星期六"];
        }else if([tempStr isEqualToString:@"Sunday"]){
            string  = [NSString stringWithFormat:@"%@",@"星期日"];
        }
        [tempArray addObject:string];
    }
    
    NSString * num =@"";
    
    for (NSString * string in tempArray) {
        if ([num isEqualToString:@""]) {
            num = [NSString stringWithFormat:@"%@",string];
        }else{
            num = [NSString stringWithFormat:@"%@,%@",num,string];
        }
    }
    
    return num;
}


#pragma 检测网络状态
+(BOOL)checkNetworkState {
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    __block BOOL isNetWork = YES;
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusUnknown) {
            ZTLog(@"未知错误");
        }
        else if (status == AFNetworkReachabilityStatusNotReachable) {
            ZTLog(@"没有网络");
            isNetWork = NO;
//            [MBProgressHUD showtex:@"当前网络未连接，请检查网络设置"];
        }
        else if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
            ZTLog(@"3G网络");
        }
        else if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
            ZTLog(@"WIFI");
        }
    }];
    
    return isNetWork;
}

@end
